import { useMcpToolsCountByServerId } from "@renderer/queries";
import logger from "@shared/logger/renderer-logger";
import type { McpServer } from "@shared/triplit/types";
import { Server } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";

interface McpServerItemProps {
  server: McpServer;
}

export function McpServerItem({ server }: McpServerItemProps) {
  const { t } = useTranslation("translation", {
    keyPrefix: "settings.mcp-settings",
  });

  const navigate = useNavigate();
  const { data: toolsCount } = useMcpToolsCountByServerId(server.id);

  const handleClick = () => {
    // Navigate immediately for better UX
    navigate(`/settings/mcp-settings/edit/${server.id}`);

    // Request tools refresh in background (non-blocking)
    logger.debug(
      "Entering MCP server edit mode, requesting tools update in background",
      {
        serverId: server.id,
        serverName: server.name,
      },
    );

    // Use setTimeout to ensure navigation happens first
    setTimeout(async () => {
      try {
        const { mcpService } = window.service;
        await mcpService.refreshAllTools();
        logger.debug(
          "MCP tools refreshed in background after entering edit mode",
          {
            serverId: server.id,
            serverName: server.name,
          },
        );
      } catch (error) {
        logger.error("Failed to refresh MCP tools in background", {
          serverId: server.id,
          serverName: server.name,
          error,
        });
      }
    }, 0);
  };

  const handleKeyDown = (event: React.KeyboardEvent) => {
    if (event.key === "Enter" || event.key === " ") {
      event.preventDefault();
      handleClick();
    }
  };

  return (
    <button
      type="button"
      className="block w-full cursor-pointer rounded-[10px] border-0 bg-white px-3.5 py-3 hover:bg-[#F9F9F9] dark:bg-bg dark:hover:bg-[#2D2D2D]"
      onClick={handleClick}
      onKeyDown={handleKeyDown}
    >
      <div className="flex w-full items-center justify-between gap-x-10">
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-muted">
            {server.icon ? (
              <span className="text-xl">{server.icon}</span>
            ) : (
              <Server className="h-5 w-5 text-muted-fg" />
            )}
          </div>
          <div className="flex flex-col gap-1">
            <h3 className="font-medium text-setting-fg text-sm">
              {server.name || server.id}
            </h3>
            {server.description && (
              <p className="text-muted-fg text-xs">{server.description}</p>
            )}
          </div>
        </div>
        <div className="text-setting-fg text-sm">
          {t("server-list.tools-count", { count: toolsCount || 0 })}
        </div>
      </div>
    </button>
  );
}
